package cn.wit.summit.chwan.ui.activity;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.adapters.ThematicListAdapter;
import cn.wit.summit.chwan.interfaces.MyScrollListener;
import cn.wit.summit.chwan.models.db.DownLoadTaskTable;
import cn.wit.summit.chwan.models.dto.GameListBaseBean;
import cn.wit.summit.chwan.models.event.DownloadEvent;
import cn.wit.summit.chwan.models.event.NotNetEvent;
import cn.wit.summit.chwan.models.request.ThematicListRequest;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.models.response.ThematicListResponse;
import cn.wit.summit.chwan.models.response.ThematicListV2Response;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.tools.downloadtool.DownLoadStatusConfig;
import cn.wit.summit.chwan.ui.base.BaseActivity;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.widgets.DownloadViewStroke;
import cn.wit.summit.chwan.widgets.ItemListView;
import cn.wit.summit.chwan.widgets.refreshLayout.SmartRefreshLayout;
import cn.wit.summit.chwan.widgets.refreshLayout.api.RefreshLayout;
import cn.wit.summit.chwan.widgets.refreshLayout.listener.OnLoadMoreListener;
import cn.wit.summit.chwan.widgets.refreshLayout.listener.OnRefreshListener;
import retrofit2.Retrofit;

/**
 * Created by Alan on 2018/5/31.
 */

public class ThematicListActivity extends BaseActivity {

    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    private String merge_topic_id;
    private int pn = 1;
    private int pc = 20;
    private ThematicListAdapter mThematicListAdapter;

    private List<ThematicListAdapter.ViewBean> viewBeans = new ArrayList<>();

    private LinearLayoutManager layoutManager;

    private RetrofitManager retrofitManager;
    private Retrofit retrofit;
    private ApiUtil api;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_thematic_list);
        ButterKnife.bind(this);

        retrofitManager = RetrofitManager.getInstance(mContext);
        retrofit = retrofitManager.getRetrofit();
        api = retrofit.create(ApiUtil.class);

        String title = getIntent().getStringExtra("title");
        if (StringUtils.isEmpty(title))
            title = "专题列表";
        setBarTitleTx(title);
        merge_topic_id = getIntent().getStringExtra("merge_topic_id");

        initList();
    }

    @Override
    public void reGetData() {
        super.reGetData();
        viewBeans.clear();
        mThematicListAdapter.notifyDataSetChanged();
        pn = 1;
        getDailyNewData();
        refreshLayout.autoRefresh();
    }

    private void initList() {
        mThematicListAdapter = new ThematicListAdapter(mAty, viewBeans);
        layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(mThematicListAdapter);
        recyclerView.setFocusable(false);
        recyclerView.addOnScrollListener(new MyScrollListener());
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(true);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                pn = 1;
                getDailyNewData();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                getDailyNewData();
            }
        });

        //触发自动刷新
//        refreshLayout.autoRefresh();
        showSkeleton();
        pn = 1;
        getDailyNewData();
    }

    private void getDailyNewData() {
        ThematicListRequest request = retrofitManager.thematicListRequest(merge_topic_id, pn, pc);
         api.getThematicList(request).enqueue(new MyCallback<ResponseBase<ThematicListV2Response>>() {
            @Override
            public void onSuccess(ResponseBase<ThematicListV2Response> model) {
                ThematicListV2Response data = model.getData_info();
                hideSkeleton();
                updataUi(data);
            }

            @Override
            public void onFailure(int code, String msg) {
                hideSkeleton();
                refreshLayout.finishRefresh(false);
                refreshLayout.finishLoadMore(false);
                refreshLayout.finishRefresh();
                showToast(msg);
                if (code == 0)
                    refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
            }
        });
    }

    private void updataUi(ThematicListV2Response bean) {

        List<ThematicListResponse> list = bean.getList();
        if (bean == null || list==null || list.size() <= 0) {
            if (pn == 1) {
                refreshLayout.finishRefresh();
            } else {
                refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
            }
            return;
        }

        if (pn == 1) {
            mThematicListAdapter.clearTempData();
            viewBeans.clear();
        }

        String path = bean.getPic_path();
        if (!StringUtils.isEmpty(path)) {
            ThematicListAdapter.ViewBean viewGameBean = new ThematicListAdapter.ViewBean(ThematicListAdapter.ViewType.TYPE_TOP_IMAGE, path);
            viewBeans.add(viewGameBean);
        }

        for (int i = 0; i < list.size(); i++) {
            List<ThematicListResponse.CollectionGameListBean> tempList = list.get(i).getCollection_game_list();
            if (tempList != null && tempList.size() > 0) {
                ThematicListAdapter.ViewBean viewBean = new ThematicListAdapter.ViewBean(ThematicListAdapter.ViewType.TYPE_TITLE, list.get(i));
                viewBeans.add(viewBean);
                for (int j = 0; j < tempList.size(); j++) {
                    ThematicListAdapter.ViewBean viewGameBean = new ThematicListAdapter.ViewBean(ThematicListAdapter.ViewType.TYPE_GAME, tempList.get(j));
                    viewBeans.add(viewGameBean);
                }
            }

            ThematicListAdapter.ViewBean viewLineBean = new ThematicListAdapter.ViewBean(ThematicListAdapter.ViewType.TYPE_LINE, null);
            viewBeans.add(viewLineBean);
        }

        if (list.size() <= 0) {
            if (pn == 1) {
                refreshLayout.finishRefresh();
            } else {
                refreshLayout.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
            }
        } else {
            if (pn == 1) {
                refreshLayout.finishRefresh();
            } else {
                refreshLayout.finishLoadMore();
            }
            pn++;
        }

        mThematicListAdapter.notifyDataSetChanged();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(DownloadEvent downloadEvent) {

        String str = mThematicListAdapter.getPoByGameId(downloadEvent.getGameId());
        if (!StringUtils.isEmpty(str)) {
            GameListBaseBean bean = mThematicListAdapter.getBeanData(Integer.valueOf(str), 0);
            if (bean == null) return;
            DownLoadTaskTable table = bean.getTaskTable();
            if (table == null) {
                table = bean.getDownloadTaskTableSimple();
            }
            table.setDownStatus(downloadEvent.status);
            if (downloadEvent.getStatus() == DownLoadStatusConfig.DOWNLOADING) {
                table.setDownprogress(downloadEvent.getProgress());
            }

            View view = layoutManager.findViewByPosition(Integer.valueOf(str));
            ItemListView itemView = view.findViewById(R.id.listItem);
            if (itemView == null) {
                return;
            }
            DownloadViewStroke dowView = itemView.getDownView();
            dowView.updateButn(table);
        }
        super.onEventMainThread(downloadEvent);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(NotNetEvent notNetEvent) {
        if (viewBeans != null && viewBeans.size() > 0
                && !notNetEvent.isHasNet) return;
        super.onEventMainThread(notNetEvent);
    }

    @Override
    protected int getSkeletonLayoutId() {
        return R.layout.activity_thematic_list_skeleton;
    }
}
